from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template

from forms import *
from user import *
from role import *
from worklist import *
from workitem import *

import worklist
import api2
import login

import sys
import os

BR = '<br />'

class MainHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write('Hello world!' + sys.version)


        
class MyBaseHandler(webapp.RequestHandler):
    params = [] # This should be defined for each handler
    values = {} # self.parseInput puts data in it

    
    def parseInput(self):
        for p in self.params:
            self.values[p] = self.request.get(p)
        return len(self.values)
            
    def generateOutput(self):
        pass
    
    def showForm(self, template_values, formName):
        path = os.path.join(os.path.dirname(__file__), formName)
        self.response.out.write(template.render(path, template_values))

    

class UserHandler(MyBaseHandler):
    params = ['command','name','pwd','phone','email','roles']
        
    def get(self):
        self.parseInput()
    
        if self.values['command'] == 'add':
            if addUser(\
                user(name=self.values['name'] \
                     ,password = self.values['pwd'] \
                     ,phone = self.values['phone'] \
                     ,email = self.values['email'] \
                     ,roles = self.values['roles'].split(','))):
                self.response.out.write('success<br />')
            else:
                self.response.out.write('fail<br />')
                
        self.response.out.write('<b>Existing Users</b><br />')
        for u in users:
            if isinstance(u, user):
                self.response.out.write(\
                    'name: %s <br /> \
                     pwd: %s <br /> \
                     phone: %s <br /> \
                     email: %s <br /> \
                     roles: %s <br />'
                     % (u.name, u.password, u.phone, u.email, u.roles))
                self.response.out.write('-----------' + BR)

        template_values = {'str_roles':rolesToString(),'current_user':login.current_user.name}
        self.showForm(template_values, 'user.html')
        
class RoleHandler(MyBaseHandler):
    params = ['command','new_role']
    
    def get(self):
        self.parseInput()

        if self.values['command'] == 'add':
            if addRole(role(name=self.values['new_role'])):
                self.response.out.write('sucess<br />')
            else:
                self.response.out.write('fail<br />')

        self.response.out.write('<b>Existing Roles:</b> ' + \
                                rolesToString() + \
                                BR)            
        template_values = {'current_user':login.current_user.name}
        self.showForm(template_values, 'role.html')
        
class WorkItemHandler(MyBaseHandler):
   params = ['command','name','status','duedate','priority','worklistId']
        
   def get(self):
        self.parseInput()
        
        if command == 'add':
            if addWorkitem(\
                workitem(itemname= itemname \
                     ,status = status \
                     ,duedate = duedate \
                     ,priority = priority \
                     ,worklistName = worklistName)):
                self.response.out.write('success<br />')
            else:
                self.response.out.write('fail<br />')
                
        self.response.out.write('<b>Existing Workitems</b><br />')
        for w in workitems:
            if isinstance(w, workitem):
                self.response.out.write(\
                    'name: %s <br /> \
                     status: %s <br /> \
                     duedate: %s <br /> \
                     priority: %s <br /> \
                     worklistName: %s <br /> '
                     % (w.name, w.status, w.duedate, w.priority, w.worklistName))
                self.response.out.write('-----------' + BR)

        template_values = {'current_user':login.current_user.name}
        self.showForm(template_values, 'workitem.html')
        
        
class WorkListHandler(MyBaseHandler):
    '''def post(self):
        command     =self.request.get('command')
        name        =self.request.get('name')
        data        =self.request.get('data        
        roles       =self.request.get('roles')

        if command == 'add':
            api2.addWorklist(worklist.worklist(assigned_roles=roles.split(','), name=name))

        self.get()

                
        
    def get(self):
        # 1 .all worklist
        self.response.out.write(BR + '1. ---- all work list - for debugging purpose' + BR)                                
        alllist = db.GqlQuery('SELECT * FROM worklist')        
        for item in alllist:
            self.response.out.write(item.name + BR)
            self.response.out.write(item.assigned_roles)
            self.response.out.write(BR)
        #2. worklist filtered by the group
        self.response.out.write(BR + '2. ---- work list that group can see - for debugging purpose' + BR)
        for item in api2.myWorklist(login.current_user):
            self.response.out.write(item.name + BR)
            self.response.out.write(item.assigned_roles)
            self.response.out.write(BR)
            #3. workitems
            for workitem in item.workitems:
                self.response.out.write(workitem.itemname)
                if workitem.isCheckedOut(login.current_user.name):
                    self.response.out.write('<font color="red">checked out</font>')
                    self.response.out.write('<input type="submit" value="Check-In" />' + BR)
                else:
                    self.response.out.write('<input type="submit" value="Check-Out" />' + BR)
                    
        values = {'current_user':login.current_user.name, 'str_roles':rolesToString()}
        path = os.path.join(os.path.dirname(__file__), 'worklist.html')
        self.response.out.write(template.render(path, values))'''

    params = ['command','name','data','roles']
        
    def get(self):
        self.parseInput()

        #self.response.out.write(self.values['roles'].split(','))
        
        if self.values['command'] == 'add':
            addWorklist(\
                worklist(name=self.values['name']\
                         ,data=self.values['data'].split(',') \
                         ,assigned_roles=self.values['roles'].split(',')))
                
            self.response.out.write('success<br />')
            #else:
            self.response.out.write('fail<br />')
    
        template_values = {'str_roles':rolesToString(),'current_user':login.current_user.name}

        self.response.out.write('<b>Existing Worklists</b><br />')
        
        if worklists is None:
            self.response.out.write('There are not worklists')
        else:
            for w in worklists:
                if isinstance(w, worklist):
                    self.response.out.write(\
                        'name: %s <br /> \
                         data: %s <br /> \
                         roles: %s <br />'
                         % (w.name, w.data, w.roles))
                    self.response.out.write('-----------' + BR)

        self.showForm(template_values, 'worklist.html')   


class LoginHandler(MyBaseHandler):
    params = ['username','password']

    login.current_user = user()
    
    def get(self):
        self.parseInput()
        
        if len(self.request.get('username')) != 0:
            #self.response.out.write(self.values['username'])
            
            q = db.GqlQuery('SELECT * FROM user WHERE name=:1 AND password=:2' \
                            , self.values['username'] \
                            , self.values['password'])
            
            if q.count()>0:
                login.current_user = q[0]
                
            if len(login.current_user.name) == 0:
                self.response.out.write('login fail')
            else:
                self.redirect('/worklist')
            
        else:
            self.showForm({'current_user':login.current_user.name}, \
                           'login.html')

        



